import os
import shutil
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QLabel, QLineEdit, QPushButton, QProgressBar, QFileDialog, 
                            QMessageBox, QGroupBox, QTextEdit, QCheckBox, QComboBox, QSpinBox, 
                            QDateEdit)
from PyQt6.QtCore import Qt, QDate
from PyQt6.QtGui import QFont, QIcon

class FileMoverApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("文件整理工具")
        self.setWindowIcon(QIcon("folder.ico"))  # 可替换为你自己的图标
        self.setGeometry(100, 100, 700, 500)
        
        # 设置全局字体
        font = QFont("Microsoft YaHei", 10)  # Windows系统常用字体
        QApplication.setFont(font)
        
        # 主窗口部件
        self.main_widget = QWidget()
        self.setCentralWidget(self.main_widget)
        
        # 主布局
        self.main_layout = QVBoxLayout()
        self.main_widget.setLayout(self.main_layout)
        
        # 添加程序说明
        self.add_description()
        
        # 添加文件操作区域
        self.add_file_operation_section()
        
        # 添加筛选条件区域
        self.add_filter_section()
        
        # 添加进度显示区域
        self.add_progress_section()
        
        # 添加状态栏
        self.statusBar().showMessage("准备就绪")
    
    def add_description(self):
        """添加程序说明区域"""
        description_box = QGroupBox("程序说明")
        description_layout = QVBoxLayout()
        
        description = QTextEdit()
        description.setReadOnly(True)
        description.setHtml("""
        <h3>文件整理工具使用说明</h3>
        <p>本工具用于将源文件夹及其子文件夹中的所有文件移动到目标文件夹，并自动删除源文件夹中的空文件夹。</p>
        <p><b>主要功能：</b></p>
        <ul>
            <li>递归移动源文件夹中的所有文件到目标文件夹</li>
            <li>自动处理同名文件（添加序号）</li>
            <li>移动完成后自动删除源文件夹中的空文件夹</li>
            <li>显示操作进度和状态</li>
            <li>支持根据文件类型、大小、日期筛选文件</li>
        </ul>
        <p><b>使用方法：</b></p>
        <ol>
            <li>选择源文件夹（包含要移动的文件）</li>
            <li>选择目标文件夹（文件将被移动到这里）</li>
            <li>设置筛选条件（可选）</li>
            <li>点击"开始整理"按钮执行操作</li>
        </ol>
        <p style="color:#FF0000">注意：操作不可逆，请确保选择的文件夹正确！</p>
        """)
        
        description_layout.addWidget(description)
        description_box.setLayout(description_layout)
        self.main_layout.addWidget(description_box)
    
    def add_file_operation_section(self):
        """添加文件操作区域"""
        operation_box = QGroupBox("文件夹设置")
        operation_layout = QVBoxLayout()
        
        # 源文件夹路径
        source_layout = QHBoxLayout()
        self.source_label = QLabel("源文件夹:")
        self.source_entry = QLineEdit()
        self.source_entry.setPlaceholderText("请选择包含要移动文件的文件夹")
        self.source_button = QPushButton("选择...")
        self.source_button.setStyleSheet("QPushButton { padding: 5px 10px; }")
        self.source_button.clicked.connect(self.select_source)
        
        source_layout.addWidget(self.source_label)
        source_layout.addWidget(self.source_entry, stretch=1)
        source_layout.addWidget(self.source_button)
        
        # 目标文件夹路径
        dest_layout = QHBoxLayout()
        self.dest_label = QLabel("目标文件夹:")
        self.dest_entry = QLineEdit()
        self.dest_entry.setPlaceholderText("请选择文件要移动到的目标文件夹")
        self.dest_button = QPushButton("选择...")
        self.dest_button.setStyleSheet("QPushButton { padding: 5px 10px; }")
        self.dest_button.clicked.connect(self.select_dest)
        
        dest_layout.addWidget(self.dest_label)
        dest_layout.addWidget(self.dest_entry, stretch=1)
        dest_layout.addWidget(self.dest_button)
        
        # 操作按钮
        self.move_button = QPushButton("开始整理")
        self.move_button.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                border: none;
                padding: 10px;
                font-size: 14px;
                font-weight: bold;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QPushButton:pressed {
                background-color: #3e8e41;
            }
        """)
        self.move_button.clicked.connect(self.move_files)
        
        operation_layout.addLayout(source_layout)
        operation_layout.addLayout(dest_layout)
        operation_layout.addWidget(self.move_button)
        operation_box.setLayout(operation_layout)
        self.main_layout.addWidget(operation_box)
    
    def add_filter_section(self):
        """添加筛选条件区域"""
        filter_box = QGroupBox("筛选条件（可选）")
        filter_layout = QVBoxLayout()
        
        # 文件类型筛选
        type_layout = QHBoxLayout()
        self.type_checkbox = QCheckBox("按文件类型筛选")
        self.type_entry = QLineEdit()
        self.type_entry.setPlaceholderText("输入文件扩展名，如.txt,.jpg")
        self.type_entry.setEnabled(False)
        self.type_checkbox.stateChanged.connect(lambda: self.toggle_filter(self.type_entry))
        
        type_layout.addWidget(self.type_checkbox)
        type_layout.addWidget(self.type_entry)
        
        # 文件大小筛选
        size_layout = QHBoxLayout()
        self.size_checkbox = QCheckBox("按文件大小筛选")
        self.size_label = QLabel("最小大小（KB）:")
        self.size_spinbox = QSpinBox()
        self.size_spinbox.setRange(0, 1000000)
        self.size_spinbox.setValue(0)
        self.size_spinbox.setEnabled(False)
        self.size_checkbox.stateChanged.connect(lambda: self.toggle_filter(self.size_spinbox))
        
        size_layout.addWidget(self.size_checkbox)
        size_layout.addWidget(self.size_label)
        size_layout.addWidget(self.size_spinbox)
        
        # 文件日期筛选
        date_layout = QHBoxLayout()
        self.date_checkbox = QCheckBox("按文件日期筛选")
        self.date_label = QLabel("最早日期:")
        self.date_edit = QDateEdit()
        self.date_edit.setCalendarPopup(True)
        self.date_edit.setDate(QDate.currentDate())
        self.date_edit.setEnabled(False)
        self.date_checkbox.stateChanged.connect(lambda: self.toggle_filter(self.date_edit))
        
        date_layout.addWidget(self.date_checkbox)
        date_layout.addWidget(self.date_label)
        date_layout.addWidget(self.date_edit)
        
        filter_layout.addLayout(type_layout)
        filter_layout.addLayout(size_layout)
        filter_layout.addLayout(date_layout)
        filter_box.setLayout(filter_layout)
        self.main_layout.addWidget(filter_box)
    
    def toggle_filter(self, widget):
        """根据复选框状态启用或禁用筛选条件输入框"""
        widget.setEnabled(self.sender().isChecked())
    
    def select_source(self):
        folder = QFileDialog.getExistingDirectory(self, "选择源文件夹")
        if folder:
            self.source_entry.setText(folder)
            self.statusBar().showMessage(f"已选择源文件夹: {folder}")
    
    def select_dest(self):
        folder = QFileDialog.getExistingDirectory(self, "选择目标文件夹")
        if folder:
            self.dest_entry.setText(folder)
            self.statusBar().showMessage(f"已选择目标文件夹: {folder}")
    
    def move_files(self):
        source_folder = self.source_entry.text()
        dest_folder = self.dest_entry.text()
        
        if not source_folder or not dest_folder:
            QMessageBox.critical(self, "错误", "请选择源文件夹和目标文件夹")
            self.statusBar().showMessage("错误: 请选择源文件夹和目标文件夹")
            return
        
        if source_folder == dest_folder:
            QMessageBox.critical(self, "错误", "源文件夹和目标文件夹不能相同")
            self.statusBar().showMessage("错误: 源文件夹和目标文件夹不能相同")
            return
        
        try:
            # 获取筛选条件
            file_types = self.type_entry.text().split(",") if self.type_checkbox.isChecked() else None
            min_size = self.size_spinbox.value() * 1024 if self.size_checkbox.isChecked() else 0
            min_date = self.date_edit.date().toPyDate() if self.date_checkbox.isChecked() else None
            
            # 获取所有文件数量用于进度条
            total_files = 0
            for root_dir, _, files in os.walk(source_folder):
                for file in files:
                    if self.is_valid_file(os.path.join(root_dir, file), file_types, min_size, min_date):
                        total_files += 1
            
            if total_files == 0:
                QMessageBox.information(self, "信息", "没有找到符合条件的文件")
                self.statusBar().showMessage("信息: 没有找到符合条件的文件")
                return
            
            self.progress.setMaximum(total_files)
            self.progress.setValue(0)
            self.status_label.setText("正在移动文件...")
            self.statusBar().showMessage("正在移动文件...")
            QApplication.processEvents()
            
            # 移动文件
            moved_files = 0
            for root_dir, _, files in os.walk(source_folder):
                for file in files:
                    if self.is_valid_file(os.path.join(root_dir, file), file_types, min_size, min_date):
                        src_path = os.path.join(root_dir, file)
                        dest_path = os.path.join(dest_folder, file)
                        
                        # 处理目标文件夹中同名文件
                        counter = 1
                        while os.path.exists(dest_path):
                            name, ext = os.path.splitext(file)
                            dest_path = os.path.join(dest_folder, f"{name}_{counter}{ext}")
                            counter += 1
                        
                        shutil.move(src_path, dest_path)
                        moved_files += 1
                        self.progress.setValue(moved_files)
                        self.status_label.setText(f"正在移动文件: {moved_files}/{total_files}")
                        QApplication.processEvents()
            
            # 删除空文件夹
            self.status_label.setText("正在删除空文件夹...")
            self.statusBar().showMessage("正在删除空文件夹...")
            QApplication.processEvents()
            
            deleted_folders = 0
            for root_dir, dirs, files in os.walk(source_folder, topdown=False):
                for dir in dirs:
                    dir_path = os.path.join(root_dir, dir)
                    try:
                        if not os.listdir(dir_path):  # 如果文件夹为空
                            os.rmdir(dir_path)
                            deleted_folders += 1
                    except Exception as e:
                        print(f"无法删除文件夹 {dir_path}: {e}")
            
            QMessageBox.information(self, "完成", 
                                  f"操作完成!\n移动了 {moved_files} 个文件\n删除了 {deleted_folders} 个空文件夹")
            self.status_label.setText("操作完成")
            self.statusBar().showMessage(f"操作完成 - 移动了 {moved_files} 个文件，删除了 {deleted_folders} 个空文件夹")
            self.progress.setValue(0)
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"发生错误: {str(e)}")
            self.status_label.setText("操作失败")
            self.statusBar().showMessage(f"错误: {str(e)}")
    
    def is_valid_file(self, file_path, file_types=None, min_size=0, min_date=None):
        """检查文件是否满足筛选条件"""
        if file_types and not any(file_path.endswith(ext.strip()) for ext in file_types):
            return False
        if min_size and os.path.getsize(file_path) < min_size:
            return False
        if min_date and os.path.getmtime(file_path) < min_date.timestamp():
            return False
        return True

    def add_progress_section(self):
        """添加进度显示区域"""
        progress_box = QGroupBox("操作进度")
        progress_layout = QVBoxLayout()
        
        self.progress = QProgressBar()
        self.progress.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.progress.setStyleSheet("""
            QProgressBar {
                border: 1px solid #ccc;
                border-radius: 3px;
                text-align: center;
                height: 20px;
            }
            QProgressBar::chunk {
                background-color: #5CD6FF;
                width: 10px;
            }
        """)
        
        self.status_label = QLabel("等待操作...")
        self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.status_label.setStyleSheet("font-size: 12px; color: #666;")
        
        progress_layout.addWidget(self.progress)
        progress_layout.addWidget(self.status_label)
        progress_box.setLayout(progress_layout)
        self.main_layout.addWidget(progress_box)

if __name__ == "__main__":
    app = QApplication([])
    
    # 设置应用程序样式
    app.setStyle("Fusion")
    
    window = FileMoverApp()
    window.show()
    app.exec()